import "../public-path";
import { createApp } from "vue";
import App from "./App.vue";
import routes from "./router/index";
import store from "./store/index";
import { createRouter, createWebHistory } from "vue-router";

let router = null;
let instance = null;
function render(props) {
  const { container } = props || { container: null };

  router = createRouter({
    history: createWebHistory(),
    routes,
  });

  router.beforeEach((to, from, next) => {
    console.log("[sub-beforeEach]", from, to);
    if (
      container &&
      window.__POWERED_BY_QIANKUN__ &&
      !to.path.includes("/sub-app")
    ) {
      next({
        path: (window.__POWERED_BY_QIANKUN__ ? "/sub-app" : "") + to.path,
      });
    } else {
      next();
    }
  });

  router.afterEach((to, from) => {
    console.log("[sub-afterEach]", from, to);
  });

  instance = createApp(App);
  instance.use(router);
  instance.use(store);
  instance.mount(container ? container.querySelector("#app") : "#app");
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render();
}

export async function bootstrap() {
  console.log("[vue] vue app bootstraped");
}
export async function mount(props) {
  console.log("[vue] props from main framework", props);
  render(props);
  // 注册应用间通信  props是基座传输过来的值，可进行token等存储使用
  // appStore(props)// 存储例子1 可作参考
  if (instance) {
    instance.config.globalProperties.$MicroMount = props;

    // 设置应用间通讯（以下两行代码）
    instance.config.globalProperties.$onGlobalStateChange =
      props.onGlobalStateChange;
    instance.config.globalProperties.$setGlobalState = props.setGlobalState;
  }

  // Cookies.set(props,'$MicroMount')
  // 注册微应用实例化函数
}
export async function unmount() {
  if (instance) {
    instance.$destroy();
    instance.$el.innerHTML = "";
    instance = null;
    router = null;
  }
}
